<?php
class Appointment extends ActiveRecord
{
	protected $dayUnixTime;
	protected $appointments = array();
	protected $startDayUnixTime; 
	protected $endDayUnixTime;		
	protected $startTime;
	protected $endTime;
	protected $updateError = array();
	protected $book = array();
	/*
	*Get appointment information by day unix time
	*
	*
	*@param dayUnixTime: unix time of day
	*return array: information about appointment || false
	*/
	public function getAppointmentsByDayTime($dayUnixTime)
	{
		$this->dayUnixTime = $dayUnixTime;
		$this->startDayUnixTime = mktime(0,0,0,date('n',$this->dayUnixTime),
											   date('j',$this->dayUnixTime),
											   date('Y',$this->dayUnixTime));
		$this->endDayUnixTime = mktime(23,59,59,date('n',$this->dayUnixTime),
										        date('j',$this->dayUnixTime),
											    date('Y',$this->dayUnixTime));
		$result = DB::connect()->createCommand()
							   ->select('id,start,end')	
							   ->from($this->tableName)
							   ->between(array('start',$this->startDayUnixTime,$this->endDayUnixTime))
							   ->where(array('and','boardroom',BOARDROOM_NUMBER))
							   ->getAll();
		if($result)
		{
			return $result;
		}
		else
		{
			return false;
		}	
	}
	/*
	*Get appointment information id of appointment
	*
	*
	*@param id: id of appointment
	*return array: information about appointment || false
	*/
	public function getAppointmentById($id)
	{
		$result = DB::connect()->createCommand()
			->select(array('appointments.id','appointments.start',
						   'appointments.end','appointments.submitted',
						   'appointments.description','appointments.employee',
						   'appointments.boardroom','employees.id',
						   'employees.name'))
			->from($this->tableName)
			->leftJoin('employees')
			->on('appointments.employee,employees.id')
			->where(array('appointments.id',$id))
			->getRow();
		if(!empty($result))
		{
			return $result;
		}
		else
		{
			return false;
		}			
	}
	/*
	*Update recurring  appointment
	*
	*
	*@param updateInfo: Array with data for updating
	*return boolean: true || false
	*/
	public function updateAppointmentOccurance($updateInfo)
	{
		if(is_array($updateInfo))
		{
			$id = $updateInfo['id'];
			if($this->get($id))
			{
				$submitted = $this->getFields('submitted');
				$submitted = $submitted[0]['submitted'];
				$appointments = DB::connect()->createCommand()
										     ->select('id,start,end')
											 ->from($this->tableName)
											 ->where(array('submitted',$submitted))
											 ->where(array('and','start',time(),'>'))
											 ->getAll();							 
				if(!empty($updateInfo['startHour']) &&
				   !empty($updateInfo['startMinute']))
				{
					$startHour = $updateInfo['startHour'];
					$startMinute = $updateInfo['startMinute'];
				}
				else
				{
					$startHour = null;
					$startMinute = null;
				}
				if(!empty($updateInfo['endHour']) &&
						!empty($updateInfo['endMinute']))
				{
					$endHour = $updateInfo['endHour'];
					$endMinute = $updateInfo['endMinute'];
				}
				else
				{
					$endHour = null;
					$endMinute = null;
				}
				if(!empty($appointments))
				{
					$i = 0;
					foreach($appointments as $key=>$value)
					{
						$i = 1;
						$result = $this->checkTimeById($value['id'],$startHour,
								$startMinute,$endHour,
								$endMinute);
						if(!$result)
						{
							$this->updateError['error'] = "Time exists on $i reccuring.";
							return $this->updateError;								
						}
					}
				}
				else
				{
					$this->updateAppointment($updateInfo);
				}
				foreach($appointments as $key=>$value)
				{
					$updateArray['id'] = $value['id'];
					$updateArray['employee'] = $updateInfo['employee'];
					$updateArray['description'] = $updateInfo['description'];
					if(isset($startHour))
					{
						$updateArray['startHour'] = $startHour;
					}
					if(isset($startMinute))
					{
						$updateArray['startMinute'] = $updateInfo['startMinute'];
					}
					if(isset($endHour))
					{
						$updateArray['endHour'] = $updateInfo['endHour'];
					}
					if(isset($endMinute))
					{
						$updateArray['endMinute'] = $updateInfo['endMinute'];
					}
					if($result = $this->updateAppointment($updateArray,false))
					{
						if(is_array($result))
						{
							$this->updateError = $result['error'];
							return $this->updateError;
						}
					}
					else
					{
						$this->updateError['error'] = 'Update error. Check database settings, please.';		
						return $this->updateError;
					}
				}
				if(empty($this->updateError))
				{
					return true;
				}
			}
			else
			{
				$this->updateError['error'] = 'There is no appointment with this id.';
				return $this->updateError;
			}	
		}
		else
		{
			return false;
		}	
	}
	/*
	*Check time for exists
	*
	*
	*@param id: id of appointment
	*@param startHour: hour of start apppointment
	*@param startMinute: minute of start appointment
	*@param endHour: hour of end apppointment
	*@param endMinute: minute of end appointment
	*return boolean: true||false
	*/
	private function checkTimeById($id,$startHour=null,$startMinute=null,
								   $endHour=null,$endMinute=null)
	{
		if($this->get($id))
		{
			if(!empty($startHour) && !empty($startMinute) or
					!empty($endHour) && !empty($endMinute))
			{
				$appointmentInfo = $this->getFields('start,end');
				if(!empty($startHour) && !empty($startMinute))
				{
					$day = date('j',$appointmentInfo[0]['start']);
					$month = date('n',$appointmentInfo[0]['start']);
					$year = date('Y',$appointmentInfo[0]['start']);
					$startTime = mktime($startHour,$startMinute,
										0,$month,$day,$year);
				}	
				else
				{
					$startTime = $appointmentInfo[0]['start'];
				}
				if(!empty($endHour) && !empty($endMinute))
				{
					$day = date('j',$appointmentInfo[0]['end']);
					$month = date('n',$appointmentInfo[0]['end']);
					$year = date('Y',$appointmentInfo[0]['end']);
					$endTime = mktime($endHour,$endMinute,0,
									  $month,$day,$year);
				}	
				else
				{
					$endTime = $appointmentInfo[0]['end'];
				}
				if($endTime <= $startTime)
				{
					return false;
				}
				$result = $this->checkTime($startTime,$endTime,$id);
				if($result)
				{
					return true;
				}
				else
				{
					return false;
				}	
			}
			else
			{	
				return true;
			}		
		}
		else
		{

			return false;
		}
	}
	/*
	*Update appointment
	*
	*
	*@param updateInfo: array with data for updating
	*@param check: true=checkTime for exists|| false=without check
	*return boolean: true||false
	*/	
	public function updateAppointment($updateInfo,$check=true)
	{
		if(is_array($updateInfo))
		{
			$id = $updateInfo['id'];
			if($this->get($id))
			{
				$appointmentInfo = $this->getAppointmentById($id);	
				if((isset($updateInfo['startHour']) &&
					isset($updateInfo['startMinute'])) ||
					(isset($updateInfo['endHour']) &&
					isset($updateInfo['endMinute'])))
				{   
					if(!empty($updateInfo['startHour']) && !empty($updateInfo['startMinute']))
					{

						$day = date('j',$appointmentInfo['start']);
						$month = date('n',$appointmentInfo['start']);
						$year = date('Y',$appointmentInfo['start']);
						$updateStartTime = mktime($updateInfo['startHour'],
												  $updateInfo['startMinute'],0,
												  $month,$day,$year);
					}
					else
					{
						$updateStartTime = $appointmentInfo['start'];
					}
					if(!empty($updateInfo['endHour']) && !empty($updateInfo['endMinute']))
					{	
						$day = date('j',$appointmentInfo['end']);
						$month = date('n',$appointmentInfo['end']);
						$year = date('Y',$appointmentInfo['end']);
						$updateEndTime = mktime($updateInfo['endHour'],$updateInfo['endMinute'],
								0,$month,$day,$year);
					}
					else
					{
						$updateEndTime = $appointmentInfo['end'];
					}
					if($updateEndTime <= $updateStartTime + 59)
					{
						$this->updateError['error'] = 'You enter incorrect information about time of appointment.';
						return $this->updateError;
					}
					if(isset($check) && $check == true)
					{
						if($this->checkTime($updateStartTime,$updateEndTime,$id))
						{
							$this->start = $updateStartTime;
							$this->end = $updateEndTime;
						}
						else
						{
							$this->updateError['error'] = 'Time exists';
							return $this->updateError;
						}
					}
					else
					{
						$this->start = $updateStartTime;
						$this->end = $updateEndTime;
					}
				}
				if(!empty($updateInfo['description']))
				{

					$this->description = $updateInfo['description'];

				}
				if(!empty($updateInfo['employee']))
				{
					
					$employee = new Employee();
					if($employee->get($updateInfo['employee']))
					{

						$this->employee = $updateInfo['employee'];
					}
					else
					{

						$this->error['error'] = 'Employee don\'t exists!';
						return $this->error['error'];
					}
				}
				if(!empty($this->fields))
				{
					if($this->save())
					{

						return true;
					}
					else
					{
						$this->error['error'] = 'Error!';
						return $this->error['error'];	
					}
				}
				else
				{
					$this->updateError['error'] = 'You dont\'t enter new information for update action.';	
					return $this->updateError;
				}
			}
			else
			{
				$this->updateError['error'] = 'There is no appointment with this id.';
				return $this->updateError;
			}	
		}
		else
		{
			return false;
		}
	}
	/*
	*Delete recurring appointment by id
	*
	*
	*@param id: id of appointment
	*return boolean: true||false
	*/	
	public function deleteOccuranceAppointment($id)
	{
		if($this->get($id))
		{
			$submitted = $this->getFields('submitted');
			$submitted =  $submitted[0]['submitted'];
			$result = DB::connect()->createCommand()
								   ->delete($this->tableName)
								   ->where(array('submitted',$submitted))
								   ->where(array('and','start',time(),'>'))
								   ->query();
			return $result;		
		}
		else
		{
			return false;
		}
	}
	/*
	*Delete appointment by employee id
	*
	*
	*@param id: id of employee
	*return boolean: true||false
	*/
	public function deleteAppointmentByEmployeeId($id)
	{
		$result = DB::connect()->createCommand()
							   ->delete($this->tableName)
							   ->where(array('employee',$id))
							   ->where(array('and','start',time(),'>'))
							   ->query();
		return $result;
	}
	/*
	*Create new appointment
	*
	*
	*@param bookInfo: array with data for creation new appointment
	*return boolean: true||false
	*/	
	public function addAppointment($bookInfo)
	{
		$this->book = $bookInfo;
		$this->submitted = time();
		$this->description = $this->book['description'];
		$this->employee = $this->book['idemployee'];
		$this->boardroom = BOARDROOM_NUMBER;
		if($this->book['recurring'] == 'yes')
		{
			if($this->book['recurringType'] == 'weekly' || 
			   $this->book['recurringType'] == 'bi-weekly')
			{
				if($this->book['recurringType'] == 'weekly')
				{
					$period = 7;
				}
				else
				{
					$period = 14;
				}
				for($i = 0; $i < $this->book['duration']; $i++)
				{
					$start =  mktime($this->book['startHour'],
									 $this->book['startMinute'],1,
									 $this->book['month'],
									 $this->book['day'] + $period * $i,
									 $this->book['year']);
					$end =  mktime($this->book['endHour'],
								   $this->book['endMinute'],1,
								   $this->book['month'],
								   $this->book['day'] + $period * $i,
								   $this->book['year']);	
					$result = $this->checkTime($start,$end);
					if(!$result)
					{
						return false;
					}	
				}	
				for($i = 0; $i < $this->book['duration']; $i++)
				{
					$start =  mktime($this->book['startHour'],
									 $this->book['startMinute'],1,
									 $this->book['month'],
									 $this->book['day'] + $period * $i,
									 $this->book['year']);
					$end =  mktime($this->book['endHour'],
								   $this->book['endMinute'],1,
								   $this->book['month'],
								   $this->book['day'] + $period * $i,
								   $this->book['year']);
					$this->start = $start;
					$this->end = $end;
					if($this->save())
					{
						continue;
					}
					else
					{
						return false;	
					}		
				}
				return true;
			}
			elseif($this->book['recurringType'] == 'monthly')
			{
				for($i = 0; $i < $this->book['duration']; $i++)
				{
					$start =  mktime($this->book['startHour'],
									 $this->book['startMinute'],1,
									 $this->book['month'] + $i,
									 $this->book['day'],
									 $this->book['year']);
					$end =  mktime($this->book['endHour'],
								   $this->book['endMinute'],1,
								   $this->book['month'] + $i,
								   $this->book['day'],
								   $this->book['year']);	
					$result = $this->checkTime($start,$end);
					if(!$result)
					{
						return false;
					}	
				}
				for($i = 0; $i < $this->book['duration']; $i++)
				{
					$start =  mktime($this->book['startHour'],
									 $this->book['startMinute'],1,
									 $this->book['month'] + $i,
									 $this->book['day'],
									 $this->book['year']);
					$end =  mktime($this->book['endHour'],
									$this->book['endMinute'],1,
									$this->book['month'] + $i,
									$this->book['day'],
									$this->book['year']);	
					$this->start = $start;
					$this->end = $end;
					if($this->save())
					{
						continue;	
					}	
					else
					{
						return false;	
					}									
				}
				return true;
			}
			else
			{
				return false;
			}
		}
		elseif ($this->book['recurring'] == 'no')
		{
			$start =  mktime($this->book['startHour'],
							 $this->book['startMinute'],1,
							 $this->book['month'],
							 $this->book['day'],
							 $this->book['year']);
			$end =  mktime($this->book['endHour'],
						   $this->book['endMinute'],1,
						   $this->book['month'],
						   $this->book['day'],
						   $this->book['year']);	
			$result = $this->checkTime($start,$end);
			if(!$result)
			{
				return false;
			}
			else
			{
				$this->start = $start;
				$this->end = $end;
				$this->save();
				return true;
			}
		}
		else
		{

			return false;
		}
	}
	/*
	*Check time for exists
	*
	*
	*@param startTime: start unix time
	*@param startTime: end unix time
	*@param appointmentId: id of appointment
	*return boolean: true||false
	*/	
	public function checkTime($startTime, $endTime, $appointmentId=null)
	{
		$this->startTime = $startTime;
		$this->endTime = $endTime;
		$query = DB::connect()->createCommand()
			->select('id')
			->from($this->tableName)
			->whereGroup("(`end` BETWEEN '$this->startTime' AND '$this->endTime' ||
						   `start` BETWEEN '$this->startTime' AND '$this->endTime' ||
						   '$this->startTime' BETWEEN `start` AND `end`) AND 
						  (`boardroom`='".BOARDROOM_NUMBER."')");
		if($appointmentId)
		{
			$result = $query->where(array('and','id',$appointmentId,'<>','()'))
				->getRow();
			if(is_array($result) && count($result) == 1)
			{
				if($result[0]['id'] = $appointmentId)
				{
					$result = null;
				}
			}
		}
		else
		{
			$result = $query->getRow();
			
		}
		if($result)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
}
